package com.wyp.didishige.activity;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.ActionBar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;

import com.umeng.analytics.MobclickAgent;
import com.umeng.update.UmengUpdateAgent;
import com.wyp.didishige.MyApplication;
import com.wyp.didishige.fragment.DiscoverFragment;
import com.wyp.didishige.fragment.NearBoyFragment;
import com.wyp.didishige.fragment.SettingsFragment;
import com.wyp.didishige.utils.IntentUtil;
import com.wyp.didishige.R;
import com.wyp.didishige.fragment.RecentFragment;
import com.wyp.didishige.model.User;

import cn.bmob.im.BmobChatManager;
import cn.bmob.im.bean.BmobInvitation;
import cn.bmob.im.bean.BmobMsg;
import cn.bmob.im.config.BmobConfig;
import cn.bmob.im.inteface.EventListener;
import cn.bmob.v3.datatype.BmobGeoPoint;


public class MainActivityV2 extends BaseActivity
        implements EventListener {

    private CharSequence mTitle;
    FragmentManager fragmentManager;
    BmobGeoPoint bmobGeoPoint;

    User user;

    private Button[] mTabs;
    private NearBoyFragment nearBoyFragment;
    private DiscoverFragment nearGirlFragment;
    private RecentFragment recentFragment;
    private SettingsFragment settingFragment;
    private Fragment[] fragments;
    private int index;
    private int currentTabIndex;
    ImageView iv_recent_tips, iv_contact_tips;//消息提示

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main_v2);

        mTitle = getTitle();
        actionBar = getSupportActionBar();
        UmengUpdateAgent.setUpdateOnlyWifi(false);
        UmengUpdateAgent.update(this);

        mTitle = getTitle();
        user = userManager.getCurrentUser(User.class);

        fragmentManager = getSupportFragmentManager();
        if (user != null) {
            user.setLastLogin(System.currentTimeMillis());
            user.update(this);
        } else {
            IntentUtil.start_activity(this, LoginActivity.class);
        }
        initNewMessageBroadCast();
        initView();
        initTab();
    }

    private void initView() {
        mTabs = new Button[3];
        mTabs[0] = (Button) findViewById(R.id.btn_index);
        mTabs[1] = (Button) findViewById(R.id.btn_contact);
        mTabs[2] = (Button) findViewById(R.id.btn_set);
        iv_recent_tips = (ImageView) findViewById(R.id.iv_recent_tips);
        iv_contact_tips = (ImageView) findViewById(R.id.iv_contact_tips);
        //把第一个tab设为选中状态
        mTabs[0].setSelected(true);
    }

    private void initTab() {

        recentFragment = new RecentFragment();
        settingFragment = new SettingsFragment();
        if (user.getSex()) {
            nearGirlFragment = new DiscoverFragment();
            fragments = new Fragment[]{nearGirlFragment, recentFragment, settingFragment};
            // 添加显示第一个fragment
            getSupportFragmentManager().beginTransaction().add(R.id.fragment_container, nearGirlFragment).
                    add(R.id.fragment_container, recentFragment).hide(recentFragment).show(nearGirlFragment).commit();
        } else {
            nearBoyFragment = new NearBoyFragment();
            fragments = new Fragment[]{nearBoyFragment, recentFragment, settingFragment};
            // 添加显示第一个fragment
            getSupportFragmentManager().beginTransaction().add(R.id.fragment_container, nearBoyFragment).
                    add(R.id.fragment_container, recentFragment).hide(recentFragment).show(nearBoyFragment).commit();
        }

    }

    /**
     * button点击事件
     *
     * @param view
     */
    public void onTabSelect(View view) {
        switch (view.getId()) {
            case R.id.btn_index:
                index = 0;
                break;
            case R.id.btn_contact:
                index = 1;
                break;
            case R.id.btn_set:
                index = 2;
                break;
        }
        if (currentTabIndex != index) {
            FragmentTransaction trx = getSupportFragmentManager().beginTransaction();
            trx.hide(fragments[currentTabIndex]);
            if (!fragments[index].isAdded()) {
                trx.add(R.id.fragment_container, fragments[index]);
            }
            trx.show(fragments[index]).commit();
        }
        mTabs[currentTabIndex].setSelected(false);
        //把当前tab设为选中状态
        mTabs[index].setSelected(true);
        currentTabIndex = index;
    }

    NewBroadcastReceiver newReceiver;

    private void initNewMessageBroadCast() {
        // 注册接收消息广播
        newReceiver = new NewBroadcastReceiver();
        IntentFilter intentFilter = new IntentFilter(BmobConfig.BROADCAST_NEW_MESSAGE);
        //优先级要低于ChatActivity
        intentFilter.setPriority(3);
        registerReceiver(newReceiver, intentFilter);
    }

    /**
     * 新消息广播接收者
     */
    private class NewBroadcastReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            //刷新界面
            refreshNewMsg(null);
            // 记得把广播给终结掉
            abortBroadcast();
        }
    }

    /**
     * 刷新界面
     */
    private void refreshNewMsg(BmobMsg message) {
        // 声音提示
        boolean isAllow = MyApplication.getInstance().getSpUtil().isAllowVoice();
        if (isAllow) {
            MyApplication.getInstance().getMediaPlayer().start();
        }
        iv_recent_tips.setVisibility(View.VISIBLE);
        //也要存储起来
        if (message != null) {
            BmobChatManager.getInstance(MainActivityV2.this).saveReceiveMessage(true, message);
        }
        if (currentTabIndex == 1) {
            //当前页面如果为会话页面，刷新此页面
            if (recentFragment != null) {
                recentFragment.refresh();
            }
        }
    }

    @Override
    public void onOffline() {
        // TODO Auto-generated method stub
        showOfflineDialog(this);
    }

    public void restoreActionBar() {
        ActionBar actionBar = getSupportActionBar();
        actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
        actionBar.setDisplayShowTitleEnabled(true);
        actionBar.setTitle(mTitle);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {

        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();

        switch (id) {
            case android.R.id.home:
                break;
            case R.id.logout:
                break;
            case R.id.about:
                break;
        }

        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        try {
            unregisterReceiver(newReceiver);
        } catch (Exception e) {
        }
    }

    long firsttime;

    @Override
    public void onBackPressed() {
        if (firsttime + 2000 > System.currentTimeMillis()) {
            MobclickAgent.onKillProcess(this);
            finish();
        } else {
            ShowToast("再按一次退出程序");
        }
        firsttime = System.currentTimeMillis();
    }

    @Override
    public void onResume() {
        super.onResume();

    }

    @Override
    public void onMessage(BmobMsg bmobMsg) {

    }

    @Override
    public void onReaded(String s, String s2) {

    }

    @Override
    public void onNetChange(boolean isNetConnected) {
        if (isNetConnected) {
            ShowToast(R.string.network_tips);
        }
    }

    @Override
    public void onAddUser(BmobInvitation bmobInvitation) {

    }
}
